# === ウェブブラウザ
require 'open-uri'
module ObjectiveKyusu::WebBrowser
  class Base < ObjectiveKyusuCore
    attr_writer :current_uri
    attr_accessor(
      :version,
      :tab_browser, # タブブラウザ？
      :url_histories,
      :history_index
    )

    def initialize()
      # default
      @version = 0.0
      @tab_browser = false
      @history_index = 0
      @url_histories = []
    end

    # === 現在表示しているURL
    def current_uri
      URI.parse(self.current_uri)
    end

    # === URLを返す。
    def current_url
      uri = current_uri
      uri.path + ((uri.query && "?#{uri.query}") || '')
    end

    # === Download
    def download
      WebBrowser.download(self.current_url)
    end

    # === リンク選択時
    def select_link(url)
      if self.url_histories.size != (self.history_index + 1)
        # 現在表示している画面が履歴の先頭以外の場合、その先を削除
        self.url_histories = self.url_histories[0, self.history_index]
      end
      self.url_histories << [self.current_url]
      self.history_index += 1
      self.current_uri = url
    end

    # === 戻るボタン押下時
    def browser_back(index = nil)
      index ||= self.history_index - 1
      unless self.url_histories[index].nil?
        self.history_index = index
        self.current_uri = self.url_histories[index]
      end
    end

    # === 進むボタン押下時
    def browser_forward(index = nil)
      index ||= self.history_index + 1
      unless self.url_histories[index].nil?
        self.history_index = index
        self.current_uri = self.url_histories[index]
      end
    end

    # === Download
    def self.download(url = "")
      # TODO: 拡張子に合ったインスタンスを返す。
    end
  end
end
